﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LiveSequence.Suite.Utils
{
  public static class TreeViewHelper
  {
    public static TreeNode SearchTreeNode(TreeView treeView, ITreeNodeComparer treeNodeComparer)
    {
      TreeNode tNode = null;
      TreeNode startTNode = treeView.SelectedNode;
      if (startTNode == null)
      {
        if (treeView.Nodes.Count > 0)
        {
          startTNode = treeView.Nodes[0];
        }
      }
      tNode = searchTreeNode(startTNode, treeNodeComparer, startTNode);
      return tNode;
    }


    private static TreeNode searchTreeNode(TreeNode currentTNode,
                            ITreeNodeComparer treeNodeComparer,
                            TreeNode startTNode)
    {
      TreeNode tNodeResult = null;
      if (currentTNode != null)
      {
        currentTNode = getNextTNode(currentTNode);
        do
        {
          if (treeNodeComparer.Match(currentTNode))
          {
            tNodeResult = currentTNode;
          }
          currentTNode = getNextTNode(currentTNode);
        } while ((tNodeResult == null) &&
                 (currentTNode != null) &&
                 (currentTNode != startTNode));
      }
      return tNodeResult;
    }

    private static TreeNode getNextTNode(TreeNode currentTNode)
    {
      TreeNode result = null;
      if (currentTNode.Nodes.Count > 0)
      {
        result = currentTNode.Nodes[0];
      }
      else if (currentTNode.NextNode != null)
      {
        result = currentTNode.NextNode;
      }
      else
      {
        TreeNode ascendent = currentTNode.Parent;
        while ((result == null) && (ascendent != null))
        {
          if (ascendent.NextNode != null)
          {
            result = ascendent.NextNode;
          }
          else if (ascendent.Parent == null)
          {
            result = ascendent.TreeView.Nodes[0];
          }
          else
          {

            ascendent = ascendent.Parent;
          }
        }
        if (ascendent == null)
        {
          result = currentTNode.TreeView.Nodes[0];
        }
      }
      return result;
    }


  }
}
